#include "mw.h"
#include "ui_mw.h"

mw::mw(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::mw)
{
    ui->setupUi(this);

    QDesktopWidget *d = QApplication::desktop();

    this->move((d->width() - this->width()) / 2, (d->height() - this->height()) / 2);

    QObject::connect(this->stalk->getInstance(), SIGNAL(connectingSignal()), this, SLOT(onConnecting()));

    QObject::connect(this->stalk->getInstance(), SIGNAL(authSuccessSignal()), this, SLOT(onAuthSuccess()));
    QObject::connect(this->stalk->getInstance(), SIGNAL(authFailedSignal()), this, SLOT(onAuthFailed()));

    QObject::connect(this->stalk->getInstance(), SIGNAL(disconnectedSignal()), this, SLOT(onDisconnected()));

    QObject::connect(this->stalk->getInstance(), SIGNAL(connectionFailedSignal()), this, SLOT(onConnectionFailed()));

    ui->errorLabel->hide();

    //StalkModel::getInstance()->init();


//    qDebug() << QFontDatabase::addApplicationFont("res/fonts/Museo_Cyrillic_500.ttf");

//    QFile museoFontFile(":/res/fonts/Museo_Cyrillic_500.ttf");
//    qDebug() << QFontDatabase::addApplicationFontFromData(museoFontFile.readAll());
//    qDebug() << museoFontFile.size();



    this->stalk = StalkModel::getInstance();
}

mw::~mw()
{
    delete ui;
}

void mw::on_connectButton_clicked()
{
//    qDebug() << this->input->waitForReadyRead(10000);
    ui->errorLabel->hide();
    if(ui->emailInput->text().isEmpty() || ui->passwordInput->text().isEmpty())
    {
        ui->errorLabel->show();
        ui->errorLabel->setText("Please enter email and password.");
    }
    else
    {
        this->stalk->auth(ui->emailInput->text(), ui->passwordInput->text());
    }
}

void mw::onConnecting()
{
    ui->connectButton->setEnabled(false);
}

//void mw::onError()
//{
//}

void mw::onAuthSuccess()
{
    this->homeWidget = new HomeWidget();
    this->homeWidget->show();
    this->close();
}

void mw::onAuthFailed()
{
    ui->connectButton->setEnabled(true);
    qDebug() << "Auth failed";
    ui->errorLabel->show();
    ui->errorLabel->setText("Wrong login or password.");
}

void mw::onDisconnected()
{
}

void mw::onConnectionFailed()
{
    ui->connectButton->setEnabled(true);
    qDebug() << "Connection failed";
    ui->errorLabel->show();
    ui->errorLabel->setText("The server is offline, sorry.");
}

void mw::on_aboutStalkButton_clicked()
{
    QDesktopServices::openUrl(QUrl("http://stalk.andrewdunai.com/"));
}
